package com.gmlive.camp.dialog.share

import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ziq.zcamp.bean.topics.TopicsShareInfo
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.ziq.base.base.BaseDialog
import com.ziq.base.extension.*
import com.ziq.zcamp.R
import com.ziq.zcamp.bean.activities.ActivitiesInfo
import com.ziq.zcamp.bean.coupon.CouponInfo
import com.ziq.zcamp.bean.life.CampLifeInfo
import com.ziq.zcamp.bean.place.PlaceDetail
import com.ziq.zcamp.bean.post.PostingDetail
import com.ziq.zcamp.bean.product.PlaceProduct
import com.ziq.zcamp.databinding.DialogShareBinding
import com.ziq.zcamp.dialog.share.*
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.WXAccount
import com.ziq.zcamp.util.ClipBoardUtil
import com.ziq.zcamp.util.PermissionHelper

/**
 * @param activity 当前的activity
 * @param tools 额外的按钮 第二行
 * @param show 微信好友 朋友圈 复制链接 生成分享图 等是否显示
 * @param source 分享来源 部分逻辑需要 埋点需要
 * @param post_type 帖子分享的类型 埋点需要
 * @param desc 详情 埋点需要
 */
class ShareDialog(val activity: FragmentActivity, val tools: List<ActionItem>, val source : String,
                  val post_type : String? = null, val desc : String ?= null, val show : List<Boolean> = listOf(true,true,true,true)) : BaseDialog(activity) {

    companion object{
        const val POST_DETAIL	= "post_detail"
        const val GOODS_DETAIL	= "goods_detail"
        const val CAMP_DETAIL	= "camp_detail"
        const val ACTIVE_DETAIL	= "active_detail"
        const val CAMP_LIFE 	= "camplife"
        const val TOPIC_DETAIL  = "topic_detail"
        const val RANK_DETAIL  = "rank_detail"
        const val CP_LIST = "cp_list"

        const val POST	        = "post"
        const val VIDEO	        = "video"
        const val ARTICLE	    = "article"
    }

    private val binding: DialogShareBinding by binding()
    private lateinit var shareActionAdapter: ActionAdapter
    private lateinit var toolActionAdapter: ActionAdapter

    private var sharePicCache:SharePicCacheInterface? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        window?.decorView?.let {
            window?.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        }

        binding.root
        binding.root.click {
            dismiss()
        }
        shareActionAdapter = ActionAdapter()
        binding.rvShareActionList.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
        binding.rvShareActionList.adapter = shareActionAdapter
        val actions = mutableListOf<ActionItem>()
        if (WXAccount.instance.isWxInstalled()) {
            if (show.isNotEmpty() && show[0]){
                actions.add(
                    ActionItem(
                        R.drawable.icon_share_wechat,
                        GlobalContextManager.getString(R.string.share_wechat)
                    )
                )
            }
            if (show.size>=2 &&show[1]){
                actions.add(
                    ActionItem(
                        R.drawable.icon_share_moments,
                        GlobalContextManager.getString(R.string.share_wechat_moments)
                    )
                )
            }
        }

        if (show.size>=3 &&show[2]){
            actions.add(
                ActionItem(
                    R.drawable.icon_share_link,
                    GlobalContextManager.getString(R.string.share_copy_link)
                )
            )
        }
        if (show.size>=4 &&show[3]){
            actions.add(
                ActionItem(
                    R.drawable.icon_share_pic,
                    GlobalContextManager.getString(R.string.share_create_pic)
                )
            )
        }
        shareActionAdapter.setData(actions)

        shareActionAdapter.setActionCallback {
            when (it) {
                GlobalContextManager.getString(R.string.share_wechat) -> {
                    sharePicCache?.let {
                        it.checkPictureBitmap {
                            it.getCoverBitmapForMiniProgram { bitmap ->
                                if(bitmap != null ){
                                    dismiss()
                                    WXAccount.instance.shareMiniProgram(bitmap, it.getTitleForMiniProgram(), path = it.getMiniProgramPath())
                                } else {
                                    val msg = GlobalContextManager.getString(R.string.share_pic_create_fail)
                                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    }

                    trackActivityShareActivityClick(0)
                }
                GlobalContextManager.getString(R.string.share_wechat_moments) -> {
                    sharePicCache?.let {
                        it.checkPictureBitmap {
                            val bitmap = it.getTotalLayoutBitmap()
                            if(bitmap != null ){
                                dismiss()
                                WXAccount.instance.sharePicture(bitmap, SendMessageToWX.Req.WXSceneTimeline)
                            } else {
                                val msg = GlobalContextManager.getString(R.string.share_pic_create_fail)
                                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                            }
                        }
                    }

                    trackActivityShareActivityClick(1)
                }
                GlobalContextManager.getString(R.string.share_copy_link) -> {
                    dismiss()
                    ClipBoardUtil.addToClipboard(GlobalContextManager.appContext!!, sharePicCache?.getLinkTxt()?:"")
                    val msg = GlobalContextManager.getString(R.string.share_copy_link_toast)
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()

                    trackActivityShareActivityClick(2)
                }
                GlobalContextManager.getString(R.string.share_create_pic) -> {
                    PermissionHelper.requestStoragePermission(activity, onGrant = {
                        dismiss()
                        ShareDialogPictureCreate(activity,source)
                            .setPostingData(postingDetail)
                            .setPlaceData(placeDetail)
                            .setPlaceProductData(placeProduct)
                            .setActivityData(activityData)
                            .setCampLifeData(campLifeData)
                            .setCouponDate(couponData)
                            .show()

                        trackActivityShareActivityClick(3)
                    })
                }
            }
        }



        toolActionAdapter = ActionAdapter()
        binding.rvShareToolList.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
        binding.rvShareToolList.adapter = toolActionAdapter
        toolActionAdapter.setData(tools)
        toolActionAdapter.setActionCallback {
            dismiss()
            actionCallBack?.invoke(it)
        }

        binding.btnCancel.click {
            dismiss()
        }
        setAnimateView(binding.root)
    }

    var postingDetail: PostingDetail? = null
    var placeDetail: PlaceDetail? = null
    var activityData : ActivitiesInfo? = null
    var campLifeData : CampLifeInfo?= null
    var topicsData : TopicsShareInfo?= null
    var couponData : CouponInfo?= null
    var placeProduct: PlaceProduct? = null

    fun setCampRankData() : ShareDialog{
        sharePicCache = SharePicCacheLayoutCampRank(context)
        binding.flCacheContainer.addView(sharePicCache as SharePicCacheLayoutCampRank, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        return this
    }

    fun setPostingData(data: PostingDetail?) : ShareDialog{
        if(data != null){
            postingDetail = data
            sharePicCache = SharePicCacheLayoutPost(context)
            binding.flCacheContainer.addView(sharePicCache as SharePicCacheLayoutPost, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            (sharePicCache as SharePicCacheLayoutPost).setPostingData(data)
        }
        return this
    }

    fun setPlaceData(data: PlaceDetail?): ShareDialog{
        if(data != null){
            placeDetail = data
            sharePicCache = SharePicCacheLayoutPlace(context)
            binding.flCacheContainer.addView(sharePicCache as SharePicCacheLayoutPlace, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            (sharePicCache as SharePicCacheLayoutPlace).setPlaceData(data)
        }
        return this
    }

    fun setActivityData(data: ActivitiesInfo?): ShareDialog{
        if(data != null){
            activityData = data
            sharePicCache = SharePicCacheLayoutActivity(context)
            binding.flCacheContainer.addView(sharePicCache as SharePicCacheLayoutActivity, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            (sharePicCache as SharePicCacheLayoutActivity).setActivityData(data)
        }
        return this
    }

    fun setCampLifeData(data: CampLifeInfo?):ShareDialog{
        if (data!=null){
            campLifeData = data
            sharePicCache = SharePicCacheLayoutCampLife(context)
            binding.flCacheContainer.addView(sharePicCache as SharePicCacheLayoutCampLife, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            (sharePicCache as SharePicCacheLayoutCampLife).setCampLifeData(data)
        }
        return this
    }

    fun setTopicsData(data: TopicsShareInfo?):ShareDialog{
        if (data != null){
            topicsData = data
            sharePicCache = SharePicCacheLayoutTopics(context)
            binding.flCacheContainer.addView(sharePicCache as SharePicCacheLayoutTopics,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)
            (sharePicCache as SharePicCacheLayoutTopics).setTopicsData(data)
        }
        return this
    }

    fun setCouponData(data: CouponInfo?):ShareDialog{
        if (data != null){
            couponData = data
            sharePicCache = SharePicCacheLayoutCoupon(context)
            binding.flCacheContainer.addView(sharePicCache as SharePicCacheLayoutCoupon,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)
            (sharePicCache as SharePicCacheLayoutCoupon).setCouponData(data)
        }
        return this
    }

    fun setPlaceProductData(data: PlaceProduct?):ShareDialog{
        if (data != null){
            placeProduct = data
            sharePicCache = SharePicCacheLayoutProduct(context)
            binding.flCacheContainer.addView(sharePicCache as SharePicCacheLayoutProduct,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)
            (sharePicCache as SharePicCacheLayoutProduct).setPlaceProductData(data)
        }
        return this
    }

    override fun show() {
        //覆写show方法对露营人生的弹窗进行特殊处理
        if (source == CAMP_LIFE){
            PermissionHelper.requestStoragePermission(activity, onGrant = {
                ShareDialogPictureCreate(activity,source)
                    .setPostingData(postingDetail)
                    .setPlaceData(placeDetail)
                    .setPlaceProductData(placeProduct)
                    .setActivityData(activityData)
                    .setCampLifeData(campLifeData)
                    .setCouponDate(couponData)
                    .show()
            })
        }else{
            super.show()
        }
    }


    var actionCallBack : ((action:String)->Unit)? = null

    fun setActionCallback(callback : (action:String)->Unit) : ShareDialog {
        actionCallBack = callback
        return this
    }

    override fun initHeight(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    override fun initWidth(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    override fun initGravity(): Int {
        return Gravity.BOTTOM or Gravity.CENTER
    }


    private fun trackActivityShareActivityClick(clickType : Int){
    }
}